
package com.zcp.notepad;

import com.zcp.notepad.NotePad.DataValue;
import com.zcp.notepad.NotePad.Notes;
import com.zcp.notepad.NotePad.WidgetInfo;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

    /**
     * 获取列表对话框。
     * 
     * @param context
     * @param title
     * @param itemsId 列表内容IDs
     * @return
     */
    public static Dialog getListDialog(final Context context, final int itemsId, View view) {
        return new AlertDialog.Builder(context).setCustomTitle(view)
                .setItems(itemsId, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        String[] items = context.getResources().getStringArray(itemsId);
                        new AlertDialog.Builder(context).setMessage(
                                "You selected: " + which + " , " + items[which]).show();
                    }
                }).create();
    }

    public static boolean isLock(Context context, int noteId) {
        Cursor mCursor = context.getContentResolver().query(NotePad.Notes.CONTENT_URI,
                new String[] {
                    NotePad.Notes.LOCK
                }, Notes._ID + "=" + noteId, null, null);
        // 增加判断防止没有数据的时候出错。
        if (mCursor != null && mCursor.moveToFirst()) {
            return (mCursor.getInt(0) == NotePad.DataValue.IS_LOCK);
        } else {
            return false;
        }
    }

    /**
     * 判断是否设置过密码
     * 
     * @param context
     * @return
     */
    public static boolean isSettingPasswrd(Context context) {
        Cursor mCursor = context.getContentResolver().query(NotePad.Settings.CONTENT_URI,
                new String[] {
                    NotePad.Settings.PASSWORD
                }, null, null, null);

        if (mCursor.moveToFirst()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 清除所有锁(即置所有为无锁状态)
     * 
     * @param context
     * @return
     */
    public static int clearAllNoteLock(Context context) {
        ContentValues values = new ContentValues();
        values.put(NotePad.Notes.LOCK, NotePad.DataValue.IS_UNLOCK);
        return context.getContentResolver().update(NotePad.Notes.CONTENT_URI, values, null, null);
    }

    /**
     * 判断是否无锁。
     * 
     * @param context
     * @return
     */
    public static boolean isAllNotLock(Context context) {
        boolean result = true;
        Cursor mCursor = context.getContentResolver().query(NotePad.Notes.CONTENT_URI,
                new String[] {
                    NotePad.Notes.LOCK
                }, null, null, null);
        if (mCursor.moveToFirst()) {
            do {
                if (mCursor.getInt(0) == NotePad.DataValue.IS_LOCK) {
                    result = false;
                    break;
                }
            } while (mCursor.moveToNext());
        }

        return result;
    }

    /**
     * 清除密码
     * 
     * @param context
     * @return
     */
    public static int clearNotePassword(Context context) {
        return context.getContentResolver().delete(NotePad.Settings.CONTENT_URI,
                NotePad.Settings._ID + " is not null", null);
    }

    /**
     * 获取确认对话框.
     * 
     * @param context
     * @param title
     * @param icon
     * @return
     */
    public static Dialog getOkCancelDialog(final Context context, String title, String message,
            Drawable icon, DialogInterface.OnClickListener okInface) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context)
                .setTitle(title)
                .setPositiveButton(R.string.alert_dialog_ok, okInface)
                .setNegativeButton(R.string.alert_dialog_cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                                /* User clicked Cancel so do some stuff */
                            }
                        });

        if (icon != null) {
            dialogBuilder.setIcon(icon);
        }
        dialogBuilder.setMessage(message);
        return dialogBuilder.create();
    }

    /**
     * @param context
     * @param title
     * @param message
     * @param icon
     * @param onckickInface 回调接口。
     * @param tagObject 用来传输数据，会返回到接口的函数参数中。
     * @return
     */
    public static Dialog getCheckPasswordDialog(final Activity context, String title,
            Drawable icon, final InterfaceOkCancelClick onckickInface, final Object tagObject) {
        LayoutInflater inflater = context.getLayoutInflater();
        View layout = inflater.inflate(R.layout.password_check_dialog,
                (ViewGroup) context.findViewById(R.id.password_check_dialog_view));
        final TextView passwordTv = (TextView) layout.findViewById(R.id.password);
        final TextView descTv = (TextView) layout.findViewById(R.id.password_title);

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setIcon(android.R.drawable.ic_dialog_info);
        dialogBuilder.setTitle(title);
        dialogBuilder.setPositiveButton(R.string.alert_dialog_ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Cursor mCursor = context.getContentResolver().query(
                                NotePad.Settings.CONTENT_URI, new String[] {
                                    NotePad.Settings.PASSWORD
                                }, null, null, null);
                        boolean isCheckOk = false;
                        if (mCursor.moveToFirst()) {
                            String queryPassword = mCursor.getString(0).toString();
                            if (passwordTv.getText().toString().equals(queryPassword)) {
                                isCheckOk = true;
                            } else {
                                descTv.setText(R.string.wrong_change_password);
                                passwordTv.setText("");
                            }
                            onckickInface
                                    .dealWithOk(isCheckOk, true, dialog, passwordTv, tagObject);
                        } else {
                            // 这种情况下就是数据库中没有密码
                            onckickInface.dealWithOk(isCheckOk, false, dialog, passwordTv,
                                    tagObject);
                        }

                    }
                });
        dialogBuilder.setNegativeButton(R.string.alert_dialog_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        onckickInface.dealWithCancel(dialog, tagObject);
                    }
                });

        if (icon != null) {
            dialogBuilder.setIcon(icon);
        }
        dialogBuilder.setView(layout);
        return dialogBuilder.create();
    }

    public static Dialog getInputTitleDialog(final Activity context, String title, Drawable icon,
            final InterfaceInputTitle onckickInface, final Object tagObject) {
        LayoutInflater inflater = context.getLayoutInflater();
        View layout = inflater.inflate(R.layout.input_title_dialog,
                (ViewGroup) context.findViewById(R.id.input_title_view));
        final EditText descTv = (EditText) layout.findViewById(R.id.input_title);

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setIcon(android.R.drawable.ic_dialog_info);
        dialogBuilder.setTitle(title);
        dialogBuilder.setPositiveButton(R.string.alert_dialog_ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String title = descTv.getText().toString();
                        if (title == null || title.trim().equals("")) {
                            Util.setDialogCanDismiss(dialog, false);
                            Toast.makeText(context, context.getString(R.string.title_cannot_null),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Util.setDialogCanDismiss(dialog, true);
                            onckickInface.dealWithOk(dialog, descTv, tagObject);
                        }
                    }
                });
        dialogBuilder.setNegativeButton(R.string.alert_dialog_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Util.setDialogCanDismiss(dialog, true);
                        onckickInface.dealWithCancel(dialog, tagObject);
                    }
                });

        if (icon != null) {
            dialogBuilder.setIcon(icon);
        }
        dialogBuilder.setView(layout);
        return dialogBuilder.create();
    }

    /**
     * @param context
     * @param title
     * @param message
     * @param icon
     * @param onckickInface 回调接口。
     * @return
     */
    public static Dialog getSettingPasswordDialog(final Activity context, String title,
            final InterfaceOkCancelClick onckickInface, final Object tagObject) {

        LayoutInflater inflater = context.getLayoutInflater();
        View layout = inflater.inflate(R.layout.password_setting_dialog,
                (ViewGroup) context.findViewById(R.id.dialog_passwod_setting));

        View newPasswordLayout = layout.findViewById(R.id.new_password_line);
        View confirmPasswordLayout = layout.findViewById(R.id.confirm_line);

        // 判断是否已经设置密码，从而控制显示不同的文本框
        final Cursor mCursor = context.getContentResolver().query(NotePad.Settings.CONTENT_URI,
                new String[] {
                    NotePad.Settings.PASSWORD
                }, null, null, null);
        newPasswordLayout.setVisibility(View.GONE);
        confirmPasswordLayout.setVisibility(View.VISIBLE);
        if (mCursor.moveToFirst()) {
            newPasswordLayout.setVisibility(View.VISIBLE);
        }

        final TextView newPasswordTv = (TextView) layout.findViewById(R.id.new_password_text);
        final TextView passwordTv = (TextView) layout.findViewById(R.id.password_text);
        final TextView confirmTv = (TextView) layout.findViewById(R.id.confirm_text);

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setIcon(android.R.drawable.ic_dialog_info);
        dialogBuilder.setTitle(title);
        dialogBuilder.setPositiveButton(R.string.alert_dialog_ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // 这种情况就是更新密码
                        if (mCursor.moveToFirst()) {
                            String memoryPassword = mCursor.getString(0);
                            // 数据库比对
                            boolean checkOk = passwordTv.getText().toString()
                                    .equals(memoryPassword);
                            // 新密码输入两次校样
                            boolean confirmOk = newPasswordTv.getText().toString()
                                    .equals(confirmTv.getText().toString());
                            newPasswordTv.setTag("update");
                            onckickInface.dealWithOk((checkOk && confirmOk), true, dialog,
                                    newPasswordTv, tagObject);
                            return;
                        }
                        // 这种情况就是第一次设置密码
                        boolean confirmOk = passwordTv.getText().toString()
                                .equals(confirmTv.getText().toString());

                        passwordTv.setTag("insert");
                        onckickInface.dealWithOk(confirmOk, true, dialog, passwordTv, tagObject);
                    }
                });
        dialogBuilder.setNegativeButton(R.string.alert_dialog_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        onckickInface.dealWithCancel(dialog, tagObject);
                    }
                });
        dialogBuilder.setView(layout);
        return dialogBuilder.create();
    }

    /**
     * @param context
     * @param title
     * @param message
     * @param icon
     * @param onckickInface 回调接口。
     * @return
     */
    public static AlertDialog getUnlockDialog(final Activity context, final int noteId,
            final InterfaceOkCancelClick onckickInface) {

        LayoutInflater inflater = context.getLayoutInflater();
        View layout = inflater.inflate(R.layout.password_setting_dialog,
                (ViewGroup) context.findViewById(R.id.dialog_passwod_setting));

        View newPasswordLayout = layout.findViewById(R.id.new_password_line);
        View confirmPasswordLayout = layout.findViewById(R.id.confirm_line);
        newPasswordLayout.setVisibility(View.GONE);
        confirmPasswordLayout.setVisibility(View.GONE);

        final TextView passwordTv = (TextView) layout.findViewById(R.id.password_text);
        final TextView descTv = (TextView) layout.findViewById(R.id.password_tv);

        final Cursor mCursor = context.getContentResolver().query(NotePad.Settings.CONTENT_URI,
                new String[] {
                    NotePad.Settings.PASSWORD
                }, null, null, null);

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setIcon(android.R.drawable.ic_dialog_info);
        dialogBuilder.setTitle(context.getString(R.string.input_password));
        dialogBuilder.setCancelable(false);
        dialogBuilder.setPositiveButton(R.string.alert_dialog_ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        if (mCursor.moveToFirst()) {
                            String memoryPassword = mCursor.getString(0);
                            // 数据库比对
                            boolean checkOk = passwordTv.getText().toString()
                                    .equals(memoryPassword);

                            if (!checkOk) {
                                descTv.setText(R.string.wrong_change_password);
                                passwordTv.setText("");
                            }
                            passwordTv.setTag(noteId);
                            onckickInface.dealWithOk(checkOk, true, dialog, passwordTv, null);
                            return;
                        }
                    }
                });
        dialogBuilder.setNegativeButton(R.string.alert_dialog_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        onckickInface.dealWithCancel(dialog, null);
                    }
                });
        dialogBuilder.setView(layout);
        return dialogBuilder.create();
    }

    /**
     * 这个方法就是用来改变dialog当前是否已经显示来控制是否要消耗--根据dialog源代码实现逻辑来实现的。
     * 
     * @param dialog
     * @param canDismiss 对话框是否能销毁。
     */
    public static void setDialogCanDismiss(DialogInterface dialog, boolean canDismiss) {
        try {
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, canDismiss);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向系统桌面增加一个叫scj的快捷键(和删除的数据要一样除了广播intent的action)。
     */
    public static void deleteShortcutToOptions(Context ctx, String title, int note_id) {
        String shortcutName = getNoteDataBaseShortName(ctx, Long.valueOf(note_id));
        // 创建一个默认的Intent
        Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");

        // 快捷方式的名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
        // 不允许重复创建
        shortcut.putExtra("duplicate", false);

        Intent intent = new Intent(ctx.getApplicationContext(), NoteEditorActivity.class);
        Uri uri = ContentUris.withAppendedId(Notes.CONTENT_URI, note_id);
        intent.setData(uri);
        intent.setAction(Intent.ACTION_EDIT);

        // 点击图标要启动的activity
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        // 快捷方式的图标
        ShortcutIconResource iconRes = Intent.ShortcutIconResource
                .fromContext(ctx, R.drawable.icon);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
        ctx.sendBroadcast(shortcut);

        setNoteDataBaseShortName(ctx, Long.valueOf(note_id), "0");
    }

    /**
     * 向系统桌面增加一个快捷键。
     */
    public static void addShortcutToOptions(final Activity ctx, String title, final int note_id) {

        InterfaceInputTitle okInface = new InterfaceInputTitle() {

            @Override
            public void dealWithOk(DialogInterface dialog, TextView inputTitle, Object tagObject) {

                String title = inputTitle.getText().toString();

                // 创建一个默认的Intent
                Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");

                // 快捷方式的名称
                shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
                // 不允许重复创建
                shortcut.putExtra("duplicate", false);

                Intent intent = new Intent(ctx.getApplicationContext(), NoteEditorActivity.class);
                Uri uri = ContentUris.withAppendedId(Notes.CONTENT_URI, note_id);
                intent.setData(uri);
                intent.putExtra("isShortcut", true);
                intent.setAction(Intent.ACTION_EDIT);

                // 点击图标要启动的activity
                shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
                // 快捷方式的图标
                ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(ctx,
                        R.drawable.icon);
                shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
                ctx.sendBroadcast(shortcut);

                setNoteDataBaseShortName(ctx, Long.valueOf(note_id), title);

            }

            @Override
            public void dealWithCancel(DialogInterface dialog, Object tagObject) {
                dialog.dismiss();

            }

        };
        String inputTitle = ctx.getString(R.string.setting_title);
        Util.getInputTitleDialog(ctx, inputTitle, null, okInface, null).show();

    }

    /**
     * 创建文件。
     * 
     * @param title
     * @param value
     */
    public static boolean createFile(String title, String value) {
        boolean result = false;
        File file = new File(Environment.getExternalStorageDirectory(), title + ".txt");
        if (file.exists()) {
            file.delete();
        }

        FileOutputStream fileOutputStream = null;
        try {
            result = file.createNewFile();

            fileOutputStream = new FileOutputStream(file);
            byte[] buf = value.getBytes();
            fileOutputStream.write(buf, 0, buf.length);
            fileOutputStream.flush();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return result;

    }

    /**
     * 打开共享对话框。
     * 
     * @param context
     * @param note_id
     * @param title
     */
    public static void shareNote(Context context, int note_id, String title) {
        String where = Notes._ID + " in (" + note_id + " )";
        Cursor mCursor = context.getContentResolver().query(Notes.CONTENT_URI, new String[] {
            Notes.NOTE
        }, where, null, null);
        if (mCursor != null) {
            if (mCursor.moveToFirst()) {
                String share = context.getString(R.string.Share);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, share + ":" + title);
                intent.putExtra(Intent.EXTRA_TEXT, mCursor.getString(0));
                context.startActivity(Intent.createChooser(intent, share));
            }
            mCursor.close();
        }
    }

    /**
     * 执行删除记事本操作，如果有快捷键也会一起被删除。
     * 
     * @param context
     * @param ids
     */
    public static int deleteNoteById(Context context, LinkedList<String> ids) {
        if (ids == null || ids.size() <= 0) {
            return 0;
        }
        StringBuffer buffer = new StringBuffer(Notes._ID + " in(");
        for (String id : ids) {
            buffer.append(id + ",");
        }
        buffer.delete(buffer.length() - 1, buffer.length());
        buffer.append(")");

        Cursor mCursor = context.getContentResolver().query(Notes.CONTENT_URI, new String[] {
                Notes._ID, Notes.TITLE
        }, buffer.toString(), null, null);
        if (mCursor.moveToFirst()) {
            do {
                Util.deleteShortcutToOptions(context, mCursor.getString(1), mCursor.getInt(0));
                Util.cancelAlarmSet(context, String.valueOf(mCursor.getInt(0)));
            } while (mCursor.moveToNext());
        }
        return context.getContentResolver().delete(Notes.CONTENT_URI, buffer.toString(), null);
    }

    /**
     * 判断是否有电话号码在这个字符串中。 3个以上,50个以下的识别为电话号码。
     * 
     * @param checkStr
     * @return 如果不是电话号码就返回size==0,如果是就返回二维数组，数组返回的是int[0]起始位置和int[1]结束位置。
     */
    public static LinkedList<int[]> isHavePhoneNumber(String checkStr) {
        LinkedList<int[]> result = new LinkedList<int[]>();
        if (checkStr == null) {
            return result;
        }

        if (checkStr.length() <= 3) {
            return result;
        }
        Pattern p = Pattern.compile("(\\d{4,50})");
        Matcher m = p.matcher(checkStr);
        int[] element = null;
        while (m.find()) {
            // 去掉边界值.
            if (m.group(0).length() != 50) {
                element = new int[2];
                element[0] = m.start(0);
                element[1] = m.end(0) - 1;
                result.add(element);
                // Log.i("222", "element[0] " + element[0] + "  element[1] " +
                // element[1]);
            }
        }
        return result;
    }

    /**
     * 判断输入的数据是否有email 地址。
     * 
     * @param source
     * @return如果不是email地址就返回size==0,如果是就返回二维数组，数组返回的是int[0]起始位置和int[1]结束位置。
     */
    public static LinkedList<int[]> isHaveEmailAddress(String source) {
        LinkedList<int[]> result = new LinkedList<int[]>();
        if (source == null) {
            return result;
        }
        // ^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$
        // 单行判断
        String strPattern = "([a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z])";

        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(source);
        int[] element = null;
        while (m.find()) {
            Log.i("222", m.group(0));
            element = new int[2];
            element[0] = m.start(0);
            element[1] = m.end(0) - 1;
            result.add(element);
            Log.i("222", "element[0] " + element[0] + "  element[1] " + element[1]);
        }
        return result;
    }

    /**
     * 判断字符串中是否包含时间(yyyy-mm-rr和mm-rr-yyyy两个格式)。
     * 
     * @param source
     * @return 只有检查这个souce时间格式中一致，不能混合检查即一行中两种时间格式混合只是检查出一种。
     */
    public static LinkedList<int[]> isHaveDateTime(String source) {
        LinkedList<int[]> result = new LinkedList<int[]>();
        if (source == null) {
            return result;
        }
        // 检查年月日
        String strPattern = "(\\d{4}-(0\\d{1}|1[0-2])-(0\\d{1}|[12]\\d{1}|3[01]))";// yyyy-mm-rr
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(source);
        int[] element = null;
        while (m.find()) {
            Log.i("222", m.group(0));
            element = new int[2];
            element[0] = m.start(0);
            element[1] = m.end(0) - 1;
            result.add(element);
            Log.i("222", "element[0] " + element[0] + "  element[1] " + element[1]);
        }

        // 检查月日年格式。
        if (result.size() == 0) {
            String strPattern1 = "((0\\d{1}|1[0-2])-(0\\d{1}|[12]\\d{1}|3[01])-\\d{4})";// mm-rr-yyyy
            p = Pattern.compile(strPattern1);
            m = p.matcher(source);
            element = null;
            while (m.find()) {
                Log.i("222", m.group(0));
                // 去掉重复的
                element = new int[2];
                element[0] = m.start(0);
                element[1] = m.end(0) - 1;
                result.add(element);
                Log.i("222", "element2[0] " + element[0] + "  element2[1] " + element[1]);
            }
        }
        return result;
    }

    /**
     * 判断字符串中是否包含URl。
     * 
     * @param source
     * @return 不包含size==0。
     */
    public static LinkedList<int[]> isHaveURl(String source) {

        LinkedList<int[]> result = new LinkedList<int[]>();
        if (source == null) {
            return result;
        }
        String strPattern = "((http://|https://|ftp://)?(www\\.){1}((\\w)+\\.){1,}(net|com|cn|org|cc|tv))";
        Pattern p = Pattern.compile(strPattern, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(source);
        int[] element = null;
        while (m.find()) {
            Log.i("222", m.group(0));
            element = new int[2];
            element[0] = m.start(0);
            element[1] = m.end(0) - 1;
            result.add(element);
            Log.i("222", "element[0] " + element[0] + "  element[1] " + element[1]);
        }

        return result;
    }

    /**
     * 通过id获取Note对象
     * 
     * @param context
     * @param noteId
     * @return
     */
    public static Note getNoteById(Context context, int noteId) {
        if (noteId < 0) {
            return null;
        }
        Note note = new Note();
        Cursor c = context.getContentResolver().query(
                ContentUris.withAppendedId(Notes.CONTENT_URI, noteId), Notes.NOTE_PROJECTION, null,
                null, null);
        if (c != null) {
            if (c.moveToFirst()) {
                note.id = noteId;
                note.color = c.getString(c.getColumnIndex(Notes.COLOR));
                note.content = c.getString(c.getColumnIndex(Notes.NOTE));
                note.isLock = c.getInt(c.getColumnIndex(Notes.LOCK)) == 1 ? true : false;
                note.title = c.getString(c.getColumnIndex(Notes.TITLE));
                note.type = c.getInt(c.getColumnIndex(Notes.TYPE));
                note.modified = c.getLong(c.getColumnIndex(Notes.MODIFIED_DATE));
                note.isRemind = c.getInt(c.getColumnIndex(Notes.REMIND)) == DataValue.IS_REMIND ? true
                        : false;
                note.remindTime = c.getString(c.getColumnIndex(Notes.REMIND_TIME));
            }
            c.close();
        }

        return note;
    }

    /**
     * 获取所有的记事本数据。
     * 
     * @param context
     * @param noteId
     * @return
     */
    public static LinkedList<Note> getAllNotes(Context context) {
        LinkedList<Note> noteList = new LinkedList<Note>();
        Cursor c = context.getContentResolver().query(Notes.CONTENT_URI, Notes.NOTE_PROJECTION,
                null, null, null);
        if (c != null && c.moveToFirst()) {
            Note note = null;
            do {
                note = new Note();
                note.id = c.getLong(c.getColumnIndex(Notes._ID));
                note.color = c.getString(c.getColumnIndex(Notes.COLOR));
                note.content = c.getString(c.getColumnIndex(Notes.NOTE));
                note.isLock = c.getInt(c.getColumnIndex(Notes.LOCK)) == 1 ? true : false;
                note.title = c.getString(c.getColumnIndex(Notes.TITLE));
                note.type = c.getInt(c.getColumnIndex(Notes.TYPE));
                note.modified = c.getLong(c.getColumnIndex(Notes.MODIFIED_DATE));
                note.isRemind = c.getInt(c.getColumnIndex(Notes.REMIND)) == DataValue.IS_REMIND ? true
                        : false;
                note.remindTime = c.getString(c.getColumnIndex(Notes.REMIND_TIME));
                noteList.add(note);
            } while (c.moveToNext());
            c.close();
        }

        return noteList;
    }

    /**
     * 生成title
     * 
     * @param text 正文
     * @return
     */
    public static String makeTitle(String text) {

        String title = text;

        while (title.startsWith(" ") || title.startsWith("\n") || title.startsWith("√ ")
                || title.startsWith("□ ")) {
            title = title.substring(1);
        }
        int length = title.length();
        title = title.substring(0, Math.min(20, length));
        if (title.indexOf("\n") != -1) {
            title = title.substring(0, title.indexOf("\n"));
        }
        return title;
    }

    /**
     * 更新指定note的widget
     * 
     * @param context
     * @param noteId
     */
    public static void updateWidget(Context context, int noteId) {
        Cursor c = context.getContentResolver().query(WidgetInfo.CONTENT_URI,
                WidgetInfo.WIDGET_PROJECTION, WidgetInfo.NOTE_ID + "=" + noteId, null, null);
        // note有关联widget时再发送广播
        if (c != null && c.getCount() > 0) {
            c.close();
            Intent i = new Intent();
            i.setAction(NoteWidgetProvider.ACTION_UPDATE_BY_NOTE);
            i.putExtra("note", Util.getNoteById(context, noteId));
            context.sendBroadcast(i);
        }
    }

    /**
     * 设置超链接。
     */
    public static void setLink(EditText edittext, String noteStr) {
        // LinkedList<int[]> isPhone = Util.isHavePhoneNumber(noteStr);
        // LinkedList<int[]> isEmail = Util.isHaveEmailAddress(noteStr);
        // LinkedList<int[]> isUrl = Util.isHaveURl(noteStr);
        // LinkedList<int[]> isDate = Util.isHaveDateTime(noteStr);
        // SpannableStringBuilder ss = new SpannableStringBuilder(noteStr);
        // //实现电话号码超链接
        // for (int[] element : isPhone) {
        // ss.setSpan(
        // new MyURLSpan(MyURLSpan.TEL, "tel:"
        // + noteStr.substring(element[0], element[1] + 1)), element[0],
        // element[1] + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // }
        // //邮件超链接
        // for (int[] element : isEmail) {
        // ss.setSpan(
        // new MyURLSpan(MyURLSpan.EMAIL, "mailto:"
        // + noteStr.substring(element[0], element[1] + 1)), element[0],
        // element[1] + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // }
        // //网络地址超链接
        // for (int[] element : isUrl) {
        // ss.setSpan(
        // new MyURLSpan(MyURLSpan.WEBURL, "http://"
        // + noteStr.substring(element[0], element[1] + 1)), element[0],
        // element[1] + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // }
        // //打开日历超链接
        // for (int[] element : isDate) {
        // ss.setSpan(
        // new MyURLSpan(MyURLSpan.CALENDER, noteStr.substring(element[0],
        // element[1] + 1)),
        // element[0], element[1] + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // }
        // edittext.setText(ss);
        // edittext.setMovementMethod(LinkMovementMethod.getInstance());
        //
        // isPhone.clear();
        // isEmail.clear();
        // isUrl.clear();
        // 设置超链接，由于设置超链接以后只能编辑第一行，于是把长按设置启动项。
        edittext.setLines(Linkify.ALL);
        edittext.setLinksClickable(false);

    }

    public static PendingIntent getNoticPin(Context context, String noteId) {
        // 定时设置.
        Intent inten = new Intent(context, NoticeBroadcastReceiver.class);
        inten.setAction("com.zcp.notePad.notice");
        inten.addCategory(noteId);// 主要是Intent.filterEquals()来判断两个Intent是否一样来判断是否是同一个提醒。
        inten.putExtra("noticeId", noteId);
        return PendingIntent.getBroadcast(context, 0, inten, 0);
    }

    /**
     * 设置自动提醒。 如果有设置提醒，由于关机以后AlarmManager
     * 原先设置的通知都会被清除,所以在NoticeBroadcastReceiver中增加开机广播，在开机以后会检查更新。
     * 
     * @param context
     * @param noteId 记事本ID.
     * @param time 长度为5 int[0]=年，int[1]=月，int[2]=日，int[3]=时，int[4]=分.
     */
    public static void setNotice(final Context context, final String noteId, int[] time) {
        MyTimePickerDialog.OnTimeSetListener listener = new MyTimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int year, int monthOfYear, int dayOfMonth,
                    int hourOfDay, int minute) {

                AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
                Calendar ca = Calendar.getInstance();
                ca.set(year, monthOfYear, dayOfMonth, hourOfDay, minute, 0);

                if (ca.getTimeInMillis() <= System.currentTimeMillis()) {
                    String text = context.getString(R.string.current_time_cannot_set);
                    Toast.makeText(context, text, Toast.LENGTH_LONG).show();
                    return;
                }

                long remindTime = ca.getTimeInMillis();

                // Log.i("222", "noteId is="+noteId);
                if (!noteId.equals("0")) {
                    am.set(AlarmManager.RTC_WAKEUP, ca.getTimeInMillis(),
                            getNoticPin(context, noteId));
                    Util.setNoteDataBaseHaveAlarm(context, Long.valueOf(noteId),
                            NotePad.DataValue.IS_REMIND, remindTime);
                } else {
                    // 防止在新建的时候设置提醒不生效
                    if (context instanceof NoteEditorActivity) {
                        NoteEditorActivity currentActivity = (NoteEditorActivity) context;
                        currentActivity.setRemindTime(remindTime);
                    }
                }

                if (context instanceof NoteEditorActivity) {
                    NoteEditorActivity currentActivity = (NoteEditorActivity) context;
                    currentActivity.refreshTitle(remindTime);
                }
            }
        };

        if (time == null) {
            Calendar ca = Calendar.getInstance();
            ca.setTimeInMillis(System.currentTimeMillis());
            time = new int[] {
                    ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DAY_OF_MONTH),
                    ca.get(Calendar.HOUR_OF_DAY), ca.get(Calendar.MINUTE), 0
            };
        }
        boolean is24hour = DateFormat.is24HourFormat(context);
        MyTimePickerDialog dialog = new MyTimePickerDialog(context, listener, time[3], time[4],
                is24hour, time[0], time[1], time[2]);
        dialog.show();

    }

    /**
     * 取消定时提醒功能。
     * 
     * @param context
     * @param noteId
     */
    public static void cancelAlarmSet(Context context, String noteId) {
        if (!noteId.equals("0")) {
            PendingIntent pi = getNoticPin(context, noteId);
            AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
            am.cancel(pi);

            Util.setNoteDataBaseHaveAlarm(context, Long.valueOf(noteId),
                    NotePad.DataValue.IS_UNREMIND, 0);

        }

        if (context instanceof NoteEditorActivity) {
            NoteEditorActivity currentActivity = (NoteEditorActivity) context;
            currentActivity.refreshTitle(0);
        }

    }

    /**
     * 根据noteID获取title。
     * 
     * @param context
     * @param noteId
     * @return
     */
    public static String getNoteTitleById(Context context, long noteId) {
        String title = "";
        Uri uri = ContentUris.withAppendedId(Notes.CONTENT_URI, noteId);
        Cursor mCursor = context.getContentResolver().query(uri, new String[] {
            NotePad.Notes.TITLE
        }, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            title = mCursor.getString(0);
        }
        return title;
    }

    /**
     * 根据noteID获取title。
     * 
     * @param context
     * @param noteId
     * @return
     */
    public static Object[] getNoteRemindInfo(Context context, long noteId) {
        Object[] info = new Object[2];
        Uri uri = ContentUris.withAppendedId(Notes.CONTENT_URI, noteId);
        Cursor mCursor = context.getContentResolver().query(uri, new String[] {
                NotePad.Notes.REMIND, NotePad.Notes.REMIND_TIME
        }, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            info[0] = mCursor.getInt(0);
            info[1] = mCursor.getString(1);
        }
        return info;
    }

    /**
     * 判断当前记事本是否设置提醒。
     * 
     * @param context
     * @param noteId
     * @return
     */
    public static boolean isRemain(Context context, long noteId) {
        if (noteId < 0) {
            return false;
        }
        int remain = 0;
        Uri uri = ContentUris.withAppendedId(Notes.CONTENT_URI, noteId);
        Cursor mCursor = context.getContentResolver().query(uri, new String[] {
            NotePad.Notes.REMIND
        }, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            remain = mCursor.getInt(0);
        }
        return remain == NotePad.DataValue.IS_REMIND;
    }

    /**
     * 更新设置当前记事本是否提醒--修改数据库中数据。
     * 
     * @param context
     * @param noteId
     * @param isRemain
     *            NotePad.DataValue.IS_REMAIN;NotePad.DataValue.IS_UNREMAIN。
     * @return
     */
    public static boolean setNoteDataBaseHaveAlarm(Context context, long noteId, int isRemain,
            long remindTime) {
        Uri uri = ContentUris.withAppendedId(Notes.CONTENT_URI, noteId);
        ContentValues values = new ContentValues();
        values.put(NotePad.Notes.REMIND, isRemain);
        values.put(NotePad.Notes.REMIND_TIME, String.valueOf(remindTime));
        int updateInt = context.getContentResolver().update(uri, values, null, null);

        return (updateInt == 1);

    }

    public static boolean setNoteDataBaseShortName(Context context, long noteId, String shortcutName) {
        Uri uri = ContentUris.withAppendedId(Notes.CONTENT_URI, noteId);
        ContentValues values = new ContentValues();
        values.put(NotePad.Notes.SHORTCUT_NAME, shortcutName);
        int updateInt = context.getContentResolver().update(uri, values, null, null);

        return (updateInt == 1);

    }

    public static String getNoteDataBaseShortName(Context context, long noteId) {
        String name = "";
        Uri uri = ContentUris.withAppendedId(Notes.CONTENT_URI, noteId);
        Cursor mCursor = context.getContentResolver().query(uri, new String[] {
            NotePad.Notes.SHORTCUT_NAME
        }, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            name = mCursor.getString(0);
        }
        return name;

    }

    /**
     * 是否昨天
     * 
     * @param when
     * @return
     */
    public static boolean isYesterday(long when) {
        Time time = new Time();
        time.set(when);

        int thenYear = time.year;
        int thenMonth = time.month;
        int thenMonthDay = time.monthDay;

        time.set(System.currentTimeMillis());
        return (thenYear == time.year) && (thenMonth == time.month)
                && (thenMonthDay == (time.monthDay - 1));
    }

    /**
     * 是否今天
     * 
     * @param when
     * @return
     */
    public static boolean isToday(long when) {
        Time time = new Time();
        time.set(when);

        int thenYear = time.year;
        int thenMonth = time.month;
        int thenMonthDay = time.monthDay;
        time.set(System.currentTimeMillis());
        return (thenYear == time.year) && (thenMonth == time.month)
                && (thenMonthDay == time.monthDay);
    }

    public static String getDateStr(Context context, long time) {
        Date day = new Date(time);
        String date;
        Date nowDay = new Date(System.currentTimeMillis());

        if (nowDay.getYear() != day.getYear()) {
            // 如果不在同一年份，则按照系统的时间格式显示日期
            java.text.DateFormat df = DateFormat.getDateFormat(context);
            date = df.format(new Date(time));

        } else if (Util.isYesterday(time)) {
            // 昨天显示yesterday
            date = context.getString(R.string.yesterday);
        } else if (Util.isToday(time)) {
            // 今天显示today
            date = context.getString(R.string.today);
        } else {
            // 其他显示月份与日期，在英文系统中显示示例 Oct 10
            date = DateUtils.formatDateTime(context, time, DateUtils.FORMAT_ABBREV_MONTH);
        }
        return date;
    }

    public static String getTimeStr(Context context, long time) {
        java.text.DateFormat df = DateFormat.getTimeFormat(context);
        return df.format(new Date(time));
    }

    /**
     * 判断字符串的编码
     * 
     * @param str
     * @return
     */
    public static String getEncoding(InputStream in, int length) {

        CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();

        detector.add(JChardetFacade.getInstance());
        Charset charset = null;
        try {
            charset = detector.detectCodepage(in, length);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return charset != null ? charset.displayName() : null;
    }

    public static void setRowColor(String color, View view) {
        if (Notes.Color.BLUE.equals(color)) {
            view.setBackgroundResource(R.drawable.note_list_blue);
        } else if (Notes.Color.PINK.equals(color)) {
            view.setBackgroundResource(R.drawable.note_list_pink);
        } else if (Notes.Color.GREEN.equals(color)) {
            view.setBackgroundResource(R.drawable.note_list_green);
        } else if (Notes.Color.ORANGE.equals(color)) {
            view.setBackgroundResource(R.drawable.note_list_orange);
        } else if (Notes.Color.PURPLE.equals(color)) {
            view.setBackgroundResource(R.drawable.note_list_purple);
        }
    }
}
